const jsonServer = require("json-server");
const jwt = require("jsonwebtoken");
const Joi = require("joi");
const md5 = require("md5");

const server = jsonServer.create();
const db = jsonServer.router("./db.json").db;

const schema = Joi.object({
  username: Joi.string().required().messages({
    "any.required": "{{#key}} is required",
    "string.empty": "{{#key}} is not allowed to be empty",
  }),
  password: Joi.string().required().messages({
    "any.required": "{{#key}} is required",
    "string.empty": "{{#key}} is not allowed to be empty",
  }),
});

server.post("/login", async (req, res) => {
  const { username, password } = req.body;
  try {
    await schema.validateAsync(req.body);
    const r = db
      .get("users")
      .find({ username, password: md5(password) })
      .value();

    if (!r) {
      return res.status(400).send({
        status: 400,
        success: false,
        message: "wrong user name or password",
      });
    }
    res.send({
      status: 200,
      success: true,
      message: "login successful",
      data: jwt.sign(r, process.env.JWT_KEY, { expiresIn: 1440 }),
    });

    next();
  } catch (err) {
    res.status(401).send({
      status: 401,
      success: false,
      message: err.details.map((el) => el.message)[0],
    });
  }
});

module.exports = () => server;
